package com.shuimin.group.logic;

import io.netty.util.CharsetUtil;
import pond.common.*;

import java.io.IOException;
import java.util.Map;

public class TokenLogic {
    private static String token ="";
    private static int expires_in =0 ;
    private static long last_token_refresh_timestamp =0;
    final private static int expire_const = 7000 * 1000;

    private static void _getAccessToken(String access_token_url, String app_id, String app_secret) throws IOException {
        long cost = S.now();
        String url = access_token_url + "&appid=" + app_id + "&secret=" + app_secret;
        HTTP.get(url, resp -> {
            try {
                String json_utf8 = STREAM.readFully(resp.getEntity().getContent(), CharsetUtil.UTF_8);
                Map map = JSON.parse(json_utf8);
                if (map.get("errorcode") != null) {
                    S.echo(map.toString());
                    throw new RuntimeException("400: error on getting access token");
                }
                token = (String) map.get("access_token");
                expires_in = S.avoidNull(Convert.toInt(map.get("expires_in")), expire_const);
                last_token_refresh_timestamp = S.now();
                S.echo("get token in " + (last_token_refresh_timestamp - cost) + "ms");
            } catch (IOException e) {
                S.echo(e.getMessage(), e);
            }
        });
    }
    private static boolean token_expires() {
        long now = S.now();
        return (now - last_token_refresh_timestamp) > expires_in;
    }
    public static String getToken(String access_token_url, String app_id, String app_secret) {
        if (token_expires()) {
            try {
                _getAccessToken(access_token_url, app_id, app_secret);
            } catch (IOException e) {
                S.echo(e.getMessage(),e);
                throw new RuntimeException(e);
            }
        }
        return token;
    }
}
